package cn.bitkit.tools.data;

import cn.bitkit.base.util.RandomUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * 
 * @author changbo
 *
 */
@Slf4j
public class CaptchaUtil {
	
	public static final int DEFAULT_WIDTH = 160;
	public static final int DEFAULT_HEIGHT = 40;
	
	public static byte[] createImage(String code) {
		return createImage(code, DEFAULT_WIDTH, DEFAULT_HEIGHT);
	}

	@SneakyThrows
	public static byte[] createImage(String code, int width, int height) {
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = image.createGraphics();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, width, height);
		
		for (int i = 0; i < 20; i++) {
			int xs = RandomUtil.random(0, width);
			int ys = RandomUtil.random(0, height);
			int xe = RandomUtil.random(0, width);
			int ye = RandomUtil.random(0, height);
			int red = RandomUtil.random(0, 255);
			int green = RandomUtil.random(0, 255);
			int blue = RandomUtil.random(0, 255);
			g.setColor(new Color(red, green, blue));
			g.drawLine(xs, ys, xe, ye);
		}
		g.setColor(Color.BLACK);
		g.drawLine(0, height/2, width, height/2);
		
		int fontSize = height-4;
        Font font = new Font("Algerian", Font.ITALIC, fontSize);
        g.setFont(font);

		int codeWidth = width / code.length();
		int codeHeight = height - 4;
		for(int i=0; i<code.length(); i++) {
			int red = RandomUtil.random(0, 255);
			int green = RandomUtil.random(0, 255);
			int blue = RandomUtil.random(0, 255);
			g.setColor(new Color(red, green, blue));
			g.drawString(""+code.charAt(i), i*codeWidth+10, codeHeight-2);
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
		return baos.toByteArray();
	}

}
